package cn.com.nes.site.service.equipment.archives.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.mybatis.agent.system.entity.Company;
import cn.com.nes.mybatis.agent.system.mapper.CompanyMapper;
import cn.com.nes.mybatis.ctce.mapper.TSbazxyMapper;
import cn.com.nes.mybatis.ctce.mapper.TSbsgjhJnMapper;
import cn.com.nes.mybatis.ctce.mapper.TZhdmbMapper;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.call.PersonalProjectPageDto;
import cn.com.nes.site.entity.vo.project.*;
import cn.com.nes.site.service.equipment.archives.CallCenterEquipmentArchivesHandle;
import cn.com.nes.site.service.equipment.archives.CtceEquipmentArchivesHandle;
import cn.com.nes.site.service.equipment.archives.OpeEquipmentArchivesHandle;
import cn.com.nes.site.service.equipment.archives.PersonalProjectManageService;
import cn.com.nes.site.service.equipment.archives.dto.*;
import cn.com.nes.site.service.project.dto.PersonalProjectDetailsDto;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class PersonalProjectManageServiceImpl implements PersonalProjectManageService {

    @Resource
    private OpeEquipmentArchivesHandle opeEquipmentArchivesHandle;

    @Resource
    private CallCenterEquipmentArchivesHandle callCenterEquipmentArchivesHandle;

    @Resource
    private CtceEquipmentArchivesHandle ctceEquipmentArchivesHandle;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private TZhdmbMapper tZhdmbMapper;

    @Resource
    private TSbazxyMapper tSbazxyMapper;

    @Resource
    private TSbsgjhJnMapper tSbsgjhJnMapper;

    @Resource(name = "transactionManager_ctceyun")
    private DataSourceTransactionManager transactionManager;

    @Resource(name = "transactionManager_ope")
    private DataSourceTransactionManager transactionManager2;

    /**
     * 保存个人项目(清洁取暖)
     * @param vo 个人项目模型
     * @return
     */
    @Override
    public PageData savePersonalProjectForClean(PersonalProjectSaveForCleanVo vo) throws Exception {
        log.debug("保存个人项目（清洁取暖） --> ddId:{}", vo.getLocationId());

        // 查询当前登录用户的公司ID
        Company agentCompany = getAgentCompany(vo.getOperateUserCompanyId());
        if (StrUtil.isEmpty(agentCompany.getNesCompanyid())) {
            throw new IllegalBusinessException("当前公司未关联厂商公司");
        }
        if (StrUtil.isEmpty(agentCompany.getCcCompanyId())) {
            throw new IllegalBusinessException("当前公司未关联客服公司");
        }

        saveCleanAndCall(vo, agentCompany);
        return PageData.ok();
    }


    public void saveCleanAndCall(PersonalProjectSaveForCleanVo vo, Company agentCompany) throws Exception {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        try {
            String LocationId = ctceEquipmentArchivesHandle.saveEquipmentArchives(vo.toCtceEquipmentArchivesBo());
            vo.setLocationId(LocationId);
            callCenterEquipmentArchivesHandle.saveEquipmentArchives(vo.toCallCenterEquipmentArchivesBo(agentCompany.getCcCompanyId(), agentCompany.getNesCompanyid()));
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw e;
        }
    }

    /**
     * 保存个人项目(设备厂商)
     * @param vo 个人项目模型
     * @return
     */
    @Override
    public PageData savePersonalProjectForManufacture(PersonalProjectSaveForManufactureVo vo) throws Exception {
        log.debug("保存个人项目（设备厂商） --> ddId:{}", vo.getDdId());

        //  如果没有ddId， 表示新增，生成 -> 地点ID、设备ID
        if (ObjectUtil.isNull(vo.getDdId())) {
            vo.setDdId(UUID.randomUUID().toString());
        }

        // 查询当前登录用户的公司ID
        Company agentCompany = getAgentCompany(vo.getOperateUserCompanyId());
        if (StrUtil.isEmpty(agentCompany.getNesCompanyid())) {
            throw new IllegalBusinessException("当前公司未关联厂商公司");
        }
        if (StrUtil.isEmpty(agentCompany.getCcCompanyId())) {
            throw new IllegalBusinessException("当前公司未关联客服公司");
        }

        saveManufactureAndCall(vo, agentCompany);
        return PageData.ok();
    }

    private void saveManufactureAndCall(PersonalProjectSaveForManufactureVo vo, Company agentCompany) throws Exception {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transactionStatus = transactionManager2.getTransaction(transactionDefinition);
        try {
            //  保存设备档案数据至运营数据库
            opeEquipmentArchivesHandle.saveEquipmentArchives(vo.toOpeEquipmentArchivesBo(agentCompany.getNesCompanyid()));
            callCenterEquipmentArchivesHandle.saveEquipmentArchives(vo.toCallCenterEquipmentArchivesBo(agentCompany.getCcCompanyId(), agentCompany.getNesCompanyid()));
            transactionManager2.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager2.rollback(transactionStatus);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取ctce字典下拉选
     * @param dicType 字典类别
     * @return
     */
    @Override
    public List<DicSelectDto> getCtceDicSelect(String dicType) throws Exception {
        List<DicSelectDto> list = tZhdmbMapper.getDicView("v_" + dicType.toLowerCase());
        if (ObjectUtil.isEmpty(list)) {
            throw new IllegalBusinessException("未找到此类别字典");
        }
        return list;
    }

    /**
     * 安装协议分页查询
     * @param vo 安装协议分页查询条件模型
     * @return
     */
    @Override
    public PageData pageInstallProtocal(InstallProtocalPageVo vo) throws Exception {
        final Page<InstallProtocalPageDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<InstallProtocalPageDto> list = tSbazxyMapper.getInstallProtocalPage(page, vo);
        return PageData.ok(page, list);
    }

    /**
     * 施工计划分页查询
     * @param vo 施工计划分页查询条件模型
     * @return
     */
    @Override
    public PageData pageConstructionPlan(ConstructionPlanPageVo vo) throws Exception {
        final Page<ConstructionPlanPageDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<ConstructionPlanPageDto> list = tSbsgjhJnMapper.getConstructionPlanPage(page, vo);
        return PageData.ok(page, list);
    }

    /**
     * 查询个人项目列表-分页
     * @param vo 个人项目分页查询模型
     * @return
     */
    @Override
    public PageData pagePersonalProject(PersonalProjectPageVo vo) throws Exception {
        // 前台没有传入公司ID且登录用户的公司ID不是 '0000'
        // 根据当前登录用户的公司ID，查询公司信息，获取到对应的运营平台厂商ID
        if (StrUtil.isEmpty(vo.getManufactureId()) && !vo.getOperateUserCompanyId().equals("0000")) {
            Company agentCompany = getAgentCompany(vo.getOperateUserCompanyId());
            vo.setManufactureId(agentCompany.getNesCompanyid());
        }

        final Page<PersonalProjectPageDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<PersonalProjectPageDto> list = callCenterEquipmentArchivesHandle.pagePersonalProject(page, vo);
        return PageData.ok(page, list);
    }

    /**
     * 查询项目详情
     * @param vo 查询模型
     * @return
     */
    @Override
    public PageData getPersonalProjectDetails(PersonalProjectDetailsQueryVo vo) throws Exception {
        PersonalProjectDetailsDto dto = new PersonalProjectDetailsDto();
        if (vo.getType() == 0) {
            dto = ctceEquipmentArchivesHandle.getPersonalProjectDeatils(vo.getSbId());
        }
        if (vo.getType() == 1) {
            dto = new PersonalProjectDetailsDto();
        }

        return PageData.ok("detail", dto);
    }

    @Override
    public List<CtceDictionaryTypeDto> getCtceDicAll() {
        List<CtceDictionaryTypeDto> dictionaryTypeList = tZhdmbMapper.getDictionaryTypeList();
        for (CtceDictionaryTypeDto ctceDictionaryTypeDto : dictionaryTypeList) {
            List<CtceDictionaryParamDto> dictionaryParamList = tZhdmbMapper.getDictionaryParamList(ctceDictionaryTypeDto.getTypeId());
            ctceDictionaryTypeDto.setParamList(dictionaryParamList);

        }
        return dictionaryTypeList;
    }

    /**
     * 删除个人项目
     * 按地点删除（可批量）
     * 按设备删除（可批量）
     * @param vo 个人项目删除模型
     * @return
     */
    @Override
    public PageData deletePersonalProject(PersonalProjectDeleteVo vo) throws Exception {


        return PageData.ok();
    }

    /**
     * 查询当前登录用户所在的热链云公司信息
     * @param agentUserCompanyId 当前登录用户公司ID
     * @return
     */
    private Company getAgentCompany(String agentUserCompanyId) throws Exception {
        // 查询当前登录的热链云用户的公司信息
        Company agentCompany = companyMapper.getCompanyUnDelete(agentUserCompanyId);
        if (ObjectUtil.isNull(agentCompany)) {
            throw new IllegalBusinessException("公司信息未查询到");
        }
        return agentCompany;
    }

}
